//
//  ViewC.m
//  drag
//
//  Created by 梁羽 on 2025/6/29.
//

#import "ViewC.h"
#import "ViewA.h"

@implementation ViewC

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor = [UIColor clearColor];
        self.minSize = 60;
        
        // 初始化矩形区域
        _rectangleRect = CGRectInset(self.bounds, 20, 20);
        _borderColor = [UIColor redColor];
        _borderWidth = 2.0;
        
        // 添加拖动手势
        UIPanGestureRecognizer *panGesture = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handlePan:)];
        [self addGestureRecognizer:panGesture];
        
        self.layer.borderWidth = 1.0;
        self.layer.borderColor = [UIColor blackColor].CGColor;
        
        // 添加按钮
        [self setupCornerButtons];  // 四个角按钮
        [self setupEdgeButtons];    // 四条边按钮
        
        [self updateButtonPositions];
    }
    return self;
}

- (void)drawRect:(CGRect)rect {
    [super drawRect:rect];
    
    // 绘制矩形
    UIBezierPath *rectanglePath = [UIBezierPath bezierPathWithRect:self.rectangleRect];
    
    [[UIColor clearColor] setFill]; // 透明填充
    [self.borderColor setStroke];   // 边框颜色
    rectanglePath.lineWidth = self.borderWidth;
    
    [rectanglePath fill];
    [rectanglePath stroke];
}

- (void)setupCornerButtons {
    NSMutableArray *buttons = [NSMutableArray array];
    
    for (NSInteger i = 0; i < 4; i++) {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame = CGRectMake(0, 0, 30, 30);
        button.backgroundColor = [UIColor orangeColor];
        button.layer.cornerRadius = 15;
        button.layer.borderWidth = 1;
        button.layer.borderColor = [UIColor blackColor].CGColor;
        button.tag = i; // 0:左上 1:右上 2:左下 3:右下
        
        UIPanGestureRecognizer *panGesture = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handleCornerPan:)];
        [button addGestureRecognizer:panGesture];
        
        [buttons addObject:button];
        [self addSubview:button];
    }
    
    self.cornerButtons = [buttons copy];
}

- (void)setupEdgeButtons {
    NSMutableArray *buttons = [NSMutableArray array];
    
    for (NSInteger i = 0; i < 4; i++) {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame = CGRectMake(0, 0, 30, 30);
        button.backgroundColor = [UIColor grayColor];
        button.layer.cornerRadius = 15;
        button.layer.borderWidth = 1;
        button.layer.borderColor = [UIColor blackColor].CGColor;
        button.tag = i + 4; // 4:上边 5:右边 6:下边 7:左边
        
        UIPanGestureRecognizer *panGesture = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handleEdgePan:)];
        [button addGestureRecognizer:panGesture];
        
        [buttons addObject:button];
        [self addSubview:button];
    }
    
    self.edgeButtons = [buttons copy];
}

- (void)handleEdgePan:(UIPanGestureRecognizer *)gesture {
    if (gesture.state == UIGestureRecognizerStateChanged) {
        UIButton *button = (UIButton *)gesture.view;
        CGPoint translation = [gesture translationInView:self];
        
        // 临时计算新位置（限制在父视图范围内）
        CGPoint newButtonCenter = CGPointMake(button.center.x + translation.x,
                                            button.center.y + translation.y);
        
        // 限制按钮不超出父视图
        CGFloat buttonRadius = button.bounds.size.width / 2;
        newButtonCenter.x = MAX(buttonRadius, MIN(newButtonCenter.x, self.bounds.size.width - buttonRadius));
        newButtonCenter.y = MAX(buttonRadius, MIN(newButtonCenter.y, self.bounds.size.height - buttonRadius));
        
        // 计算视图需要的变化量
        CGFloat deltaX = newButtonCenter.x - button.center.x;
        CGFloat deltaY = newButtonCenter.y - button.center.y;
        
        // 根据按钮tag确定调整哪条边（完全固定对边）
        CGRect newRectangleRect = self.rectangleRect;
        CGPoint centerAdjustment = CGPointZero;
        
        switch (button.tag) {
            case 4: { // 上边 - 完全固定下边
                CGFloat minY = CGRectGetMaxY(newRectangleRect) - self.minSize;
                newRectangleRect.origin.y = MIN(newButtonCenter.y, minY);
                newRectangleRect.size.height = CGRectGetMaxY(self.rectangleRect) - newRectangleRect.origin.y;
                centerAdjustment.y = (newRectangleRect.origin.y - self.rectangleRect.origin.y) / 2;
                break;
            }
            case 5: { // 右边 - 完全固定左边
                newRectangleRect.size.width = MAX(self.minSize, self.rectangleRect.size.width + deltaX);
                centerAdjustment.x = deltaX / 2;
                break;
            }
            case 6: { // 下边 - 完全固定上边
                newRectangleRect.size.height = MAX(self.minSize, self.rectangleRect.size.height + deltaY);
                centerAdjustment.y = deltaY / 2;
                break;
            }
            case 7: { // 左边 - 完全固定右边
                CGFloat minX = CGRectGetMaxX(newRectangleRect) - self.minSize;
                newRectangleRect.origin.x = MIN(newButtonCenter.x, minX);
                newRectangleRect.size.width = CGRectGetMaxX(self.rectangleRect) - newRectangleRect.origin.x;
                centerAdjustment.x = (newRectangleRect.origin.x - self.rectangleRect.origin.x) / 2;
                break;
            }
        }
        
        // 计算需要的视图C的新frame（矩形+外边距）
        CGFloat margin = 20;
        CGRect newCFrame = CGRectInset(newRectangleRect, -margin, -margin);
        
        // 限制视图C的最大尺寸不超过容器视图
        newCFrame.size.width = MIN(self.containerView.bounds.size.width, newCFrame.size.width);
        newCFrame.size.height = MIN(self.containerView.bounds.size.height, newCFrame.size.height);
        
        // 调整视图C的位置（完全固定对边）
        CGPoint oldCenter = self.center;
        oldCenter.x += centerAdjustment.x;
        oldCenter.y += centerAdjustment.y;
        
        // 应用新frame和center
        CGRect oldFrame = self.frame;
        self.frame = newCFrame;
        self.center = oldCenter;
        
        // 检查并调整位置，确保视图C不超出容器
        CGRect containerBounds = self.containerView.bounds;
        BOOL needAdjust = NO;
        CGRect adjustedFrame = self.frame;
        
        if (CGRectGetMinX(adjustedFrame) < 0) {
            adjustedFrame.origin.x = 0;
            needAdjust = YES;
        }
        if (CGRectGetMinY(adjustedFrame) < 0) {
            adjustedFrame.origin.y = 0;
            needAdjust = YES;
        }
        if (CGRectGetMaxX(adjustedFrame) > containerBounds.size.width) {
            adjustedFrame.origin.x = containerBounds.size.width - adjustedFrame.size.width;
            needAdjust = YES;
        }
        if (CGRectGetMaxY(adjustedFrame) > containerBounds.size.height) {
            adjustedFrame.origin.y = containerBounds.size.height - adjustedFrame.size.height;
            needAdjust = YES;
        }
        
        if (needAdjust) {
            [UIView animateWithDuration:0.2 animations:^{
                self.frame = adjustedFrame;
            }];
        }
        
        // 更新矩形区域(相对于新的视图C bounds)
        _rectangleRect = CGRectInset(self.bounds, margin, margin);
        
        [gesture setTranslation:CGPointZero inView:self];
        [self updateButtonPositions];
        [self setNeedsDisplay];
    }
    else if (gesture.state == UIGestureRecognizerStateEnded ||
             gesture.state == UIGestureRecognizerStateCancelled) {
        [self notifyRectanglePathUpdate];
    }
}

- (void)handleCornerPan:(UIPanGestureRecognizer *)gesture {
    if (gesture.state == UIGestureRecognizerStateChanged) {
        UIButton *button = (UIButton *)gesture.view;
        CGPoint translation = [gesture translationInView:self];
        
        // 临时计算新位置
        CGPoint newButtonCenter = CGPointMake(button.center.x + translation.x,
                                            button.center.y + translation.y);
        
        // 根据按钮tag确定调整哪个方向
        CGRect newRectangleRect = self.rectangleRect;
        switch (button.tag) {
            case 0: { // 左上
                CGFloat deltaX = newButtonCenter.x - button.center.x;
                CGFloat deltaY = newButtonCenter.y - button.center.y;
                newRectangleRect.origin.x += deltaX;
                newRectangleRect.origin.y += deltaY;
                newRectangleRect.size.width -= deltaX;
                newRectangleRect.size.height -= deltaY;
                break;
            }
            case 1: { // 右上
                CGFloat deltaX = newButtonCenter.x - button.center.x;
                CGFloat deltaY = newButtonCenter.y - button.center.y;
                newRectangleRect.origin.y += deltaY;
                newRectangleRect.size.width += deltaX;
                newRectangleRect.size.height -= deltaY;
                break;
            }
            case 2: { // 左下
                CGFloat deltaX = newButtonCenter.x - button.center.x;
                CGFloat deltaY = newButtonCenter.y - button.center.y;
                newRectangleRect.origin.x += deltaX;
                newRectangleRect.size.width -= deltaX;
                newRectangleRect.size.height += deltaY;
                break;
            }
            case 3: { // 右下
                CGFloat deltaX = newButtonCenter.x - button.center.x;
                CGFloat deltaY = newButtonCenter.y - button.center.y;
                newRectangleRect.size.width += deltaX;
                newRectangleRect.size.height += deltaY;
                break;
            }
        }
        
        // 确保矩形不会太小
        newRectangleRect.size.width = MAX(20, newRectangleRect.size.width);
        newRectangleRect.size.height = MAX(20, newRectangleRect.size.height);
        
        // 计算需要的视图C的新frame（矩形+外边距）
        CGFloat margin = 20; // 矩形到视图C边缘的距离
        CGRect newCFrame = CGRectInset(newRectangleRect, -margin, -margin);
        
        // 限制视图C的最小尺寸
        newCFrame.size.width = MAX(self.minSize, newCFrame.size.width);
        newCFrame.size.height = MAX(self.minSize, newCFrame.size.height);
        
        // 限制视图C的最大尺寸不超过容器视图
        newCFrame.size.width = MIN(self.containerView.bounds.size.width, newCFrame.size.width);
        newCFrame.size.height = MIN(self.containerView.bounds.size.height, newCFrame.size.height);
        
        // 调整视图C的位置，确保不超出容器
        CGPoint oldCenter = self.center;
        self.frame = newCFrame;
        self.center = oldCenter;
        
        // 检查并调整位置，确保视图C不超出容器
        CGRect containerBounds = self.containerView.bounds;
        if (CGRectGetMinX(self.frame) < 0) {
            self.frame = CGRectMake(0, CGRectGetMinY(self.frame),
                                  CGRectGetWidth(self.frame), CGRectGetHeight(self.frame));
        }
        if (CGRectGetMinY(self.frame) < 0) {
            self.frame = CGRectMake(CGRectGetMinX(self.frame), 0,
                                  CGRectGetWidth(self.frame), CGRectGetHeight(self.frame));
        }
        if (CGRectGetMaxX(self.frame) > containerBounds.size.width) {
            self.frame = CGRectMake(containerBounds.size.width - CGRectGetWidth(self.frame),
                                  CGRectGetMinY(self.frame),
                                  CGRectGetWidth(self.frame), CGRectGetHeight(self.frame));
        }
        if (CGRectGetMaxY(self.frame) > containerBounds.size.height) {
            self.frame = CGRectMake(CGRectGetMinX(self.frame),
                                  containerBounds.size.height - CGRectGetHeight(self.frame),
                                  CGRectGetWidth(self.frame), CGRectGetHeight(self.frame));
        }
        
        // 更新矩形区域(相对于新的视图C bounds)
        _rectangleRect = CGRectInset(self.bounds, margin, margin);
        
        [gesture setTranslation:CGPointZero inView:self];
        [self updateButtonPositions];
        [self setNeedsDisplay];
    }
    else if (gesture.state == UIGestureRecognizerStateEnded ||
             gesture.state == UIGestureRecognizerStateCancelled) {
        [self notifyRectanglePathUpdate];
    }
}

- (void)updateButtonPositions {
    // 更新角按钮位置
    self.cornerButtons[0].center = CGPointMake(CGRectGetMinX(self.rectangleRect), CGRectGetMinY(self.rectangleRect));
    self.cornerButtons[1].center = CGPointMake(CGRectGetMaxX(self.rectangleRect), CGRectGetMinY(self.rectangleRect));
    self.cornerButtons[2].center = CGPointMake(CGRectGetMinX(self.rectangleRect), CGRectGetMaxY(self.rectangleRect));
    self.cornerButtons[3].center = CGPointMake(CGRectGetMaxX(self.rectangleRect), CGRectGetMaxY(self.rectangleRect));
    
    // 更新边按钮位置
    self.edgeButtons[0].center = CGPointMake(CGRectGetMidX(self.rectangleRect), CGRectGetMinY(self.rectangleRect)); // 上边
    self.edgeButtons[1].center = CGPointMake(CGRectGetMaxX(self.rectangleRect), CGRectGetMidY(self.rectangleRect)); // 右边
    self.edgeButtons[2].center = CGPointMake(CGRectGetMidX(self.rectangleRect), CGRectGetMaxY(self.rectangleRect)); // 下边
    self.edgeButtons[3].center = CGPointMake(CGRectGetMinX(self.rectangleRect), CGRectGetMidY(self.rectangleRect)); // 左边
    
    // 确保按钮不超出父视图
    NSArray *allButtons = [self.cornerButtons arrayByAddingObjectsFromArray:self.edgeButtons];
    for (UIButton *button in allButtons) {
        CGRect buttonFrame = button.frame;
        
        // 限制x坐标
        if (CGRectGetMinX(buttonFrame) < 0) {
            buttonFrame.origin.x = 0;
        }
        if (CGRectGetMaxX(buttonFrame) > self.bounds.size.width) {
            buttonFrame.origin.x = self.bounds.size.width - buttonFrame.size.width;
        }
        
        // 限制y坐标
        if (CGRectGetMinY(buttonFrame) < 0) {
            buttonFrame.origin.y = 0;
        }
        if (CGRectGetMaxY(buttonFrame) > self.bounds.size.height) {
            buttonFrame.origin.y = self.bounds.size.height - buttonFrame.size.height;
        }
        
        button.frame = buttonFrame;
    }
    
    // 更新菜单栏位置
    if ([self.containerView isKindOfClass:[ViewA class]]) {
        [(ViewA *)self.containerView updateMenuBarPosition];
    }
}

- (void)layoutSubviews {
    [super layoutSubviews];
    
    // 视图布局变化时更新按钮位置
    [self updateButtonPositions];
}

- (void)handlePan:(UIPanGestureRecognizer *)gesture {
    if (gesture.state == UIGestureRecognizerStateBegan) {
        _panStartLocation = [gesture locationInView:self.superview];
    }
    else if (gesture.state == UIGestureRecognizerStateChanged) {
        CGPoint currentLocation = [gesture locationInView:self.superview];
        CGPoint translation = CGPointMake(currentLocation.x - _panStartLocation.x,
                                         currentLocation.y - _panStartLocation.y);
        
        CGPoint newCenter = CGPointMake(self.center.x + translation.x,
                                       self.center.y + translation.y);
        
        // 限制不超出容器边界
        CGFloat minX = self.frame.size.width / 2;
        CGFloat maxX = self.containerView.frame.size.width - self.frame.size.width / 2;
        CGFloat minY = self.frame.size.height / 2;
        CGFloat maxY = self.containerView.frame.size.height - self.frame.size.height / 2;
        
        newCenter.x = MAX(minX, MIN(newCenter.x, maxX));
        newCenter.y = MAX(minY, MIN(newCenter.y, maxY));
        
        self.center = newCenter;
        _panStartLocation = currentLocation;
        
        // 更新菜单栏位置
        if ([self.containerView isKindOfClass:[ViewA class]]) {
            [(ViewA *)self.containerView updateMenuBarPosition];
        }
    }
    else if (gesture.state == UIGestureRecognizerStateEnded ||
             gesture.state == UIGestureRecognizerStateCancelled) {
        [self notifyRectanglePathUpdate];
    }
}

- (void)notifyRectanglePathUpdate {
    UIBezierPath *ellipsePath = [self currentRectanglePathInView:self.containerView];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"8888-9999" object:nil userInfo:@{@"path": ellipsePath, @"type": @"2"}];
}

- (UIBezierPath *)currentRectanglePathInView:(UIView *)view {
    CGRect rect = [self convertRect:self.rectangleRect toView:view];
    return [UIBezierPath bezierPathWithRect:rect];
}
@end
